import { reactive, toRefs } from 'vue'
import { PageResponse, Pagination } from '@/config/common'

interface State<T> {
  pagination: {
    current: number
    pageSize: number
    total: number
  },
  loading: boolean,
  list: T[]
}

export function usePagination<T> (endpoint: Function) {
  const state = reactive<State<T>>({
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0
    },
    loading: false,
    list: []
  })

  const loadData = async () => {
    state.loading = true
    const {
      current,
      pageSize: size
    } = state.pagination
    try {
      const res: PageResponse<T> = await endpoint({
        current,
        size
      })
      // @ts-ignore
      state.list = res.records
      state.pagination.total = res.total
    } finally {
      state.loading = false
    }
  }

  const handleChange = (page: Pagination) => {
    state.pagination.current = page.current
    state.pagination.pageSize = page.pageSize
    loadData()
  }

  const search = () => {
    state.pagination.current = 1
    loadData()
  }

  return {
    ...toRefs(state),
    search,
    handleChange,
    loadData
  }
}

export function useModalForm<T extends Object> (defaultData: T, endpoint: Function) {
  const state = reactive({
    defaultData,
    formData: defaultData,
    loading: false,
    visible: false,
    title: ''
  })

  const open = async (title: string, data?: any) => {
    state.loading = true
    state.formData = data ? (await endpoint(data)) : { ...state.defaultData }
    state.visible = true
    state.title = title
    state.loading = false
  }

  const close = () => {
    state.visible = false
  }

  return {
    ...toRefs(state),
    open,
    close
  }
}
